<?php
/**
* Numedia Studio Framework
* 
* Install script to create database
* tables and then insert default data.
* Only run if theme is being activated
* for the first time.
*
*/

function ns_install(){

	$check = get_option( ns_theme_slug.'_first_install_check' );

	if ( $check != "set" ) 
	{				
		// Create pages and assign templates
        ns_create_pages( ns_get_custom_pages() );
		
		// Create categories
        ns_create_categories( generate_categories() );
		
		// Create alphabet
        ns_create_categories( generate_alphabet() );

		// Add marker so it doesn't run in future
		update_option( ns_theme_slug.'_first_install_check', "set" );
	
		// Update the default values
		global $install_default_values;
		ns_default_values( $install_default_values );
	}

}
add_action('admin_init', 'ns_install');

// UNINSTALL THEME AND SET DEFAULT OPTIONS
function ns_theme_uninstall(){

	// Delete pages
	ns_delete_pages( ns_get_custom_pages() );
	
	// Delete install flag
	delete_option( ns_theme_slug.'_first_install_check' );
}

/**
* Set default ns option values
* this is a shortcut to manually set
* options on the wp admin dashboard.
*
*/

function ns_default_values( $options ) 
{	
	if( empty($options) ) return;
	
	foreach ($options as $option ) 
	{
		update_option( $option['name'], $option['value'] );
	}

}

// Create the ns pages and assign the templates to them
// first check and make sure this page doesn't already exist
function ns_create_pages( $custom_pages ) 
{
	if( empty($custom_pages) ) return;
	
    global $wpdb; 
	
	foreach ($custom_pages as $page ) 
	{	
		// Prepare the page
		$my_page = array(
		'post_status' => 'publish',
		'post_type' => 'page',
		'post_author' => 1,
		'post_name' => $page["post_name"],
		'post_title' => $page["post_title"]
		);
		
		$sql = "SELECT ID FROM " . $wpdb->posts . " WHERE post_name = '". $page["post_name"] ."' LIMIT 1";
	
		$wpdb->get_results($sql);
	
		if($wpdb->num_rows == 0) {
	
			// Insert the page into the database
			$page_id = wp_insert_post($my_page);
	
			// Assign the page template to the new page
			update_post_meta($page_id, '_wp_page_template', $page["_wp_page_template"]);
		}
	}
}


// Create the ns categories
// first check and make sure this category doesn't already exist
function ns_create_categories( $categories ) 
{
	if( empty($categories) ) return;
	
    global $wpdb; 
	
	foreach ($categories as $category ) 
	{
		wp_insert_term( $category[0], 'category',  array( 'slug' => $category[0] ) );
	}
}


// Create the np pages and assign the templates to them
// first check and make sure this page doesn't already exist
function ns_delete_pages( $custom_pages ) 
{
	if( empty($custom_pages) ) return;
	
	foreach ($custom_pages as $custom_page ) 
	{	
		$page = get_page_by_title( $custom_page["post_title"] );
		
		$result = wp_delete_post( $page->ID, true );
	}
}


?>